import React, { useRef, useState } from "react";
import StoTable, { StoTableApi } from "../components/StoTable/StoTable";
import { getStudents } from "../common/mockdata";
import StoPaginator from "../components/StoPaginator/StoPaginator";

const students = getStudents(20);
let page = 1;
const pageSize = 10;

const formatter = {
  avatar: (student: any) => (
    <a href={`/${student.id}`}>
      <img src={student.avatar} alt="" />
    </a>
  ),

  name: (student: any) => (
    <a style={{ fontWeight: "bold" }} href={`/${student.id}`}>
      {student.name}
    </a>
  ),
};

export default function TablePagiDemo() {
  // const [page, setPage] = useState(1);

  // useRef<子组件暴露出来的API类型>
  const childRef = useRef<StoTableApi>(null);

  return (
    <div style={{ width: 1000 }}>
      <h3>TableDemo</h3>
      <button onClick={() => childRef.current!.turnToPage(--page)}>
        上一页
      </button>
      <button onClick={() => (childRef.current as any).turnToPage(++page)}>
        下一页
      </button>

      <StoTable
        ref={childRef}
        data={students}
        pageSize={pageSize}
        sortableKeys={["id", "name", "age", "gender"]}
        formatter={formatter}
        currentPage={page}
      ></StoTable>

      <StoPaginator
        totalPages={Math.ceil(students.length / pageSize)}
        currentPage={1}
        onPageChange={(n: number) => {
          console.log("onPageChange", n);
          childRef.current?.turnToPage(n);
        }}
      ></StoPaginator>
    </div>
  );
}
